package com.demo.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.demo.utils.SseUtils;
import com.demo.utils.UUIDUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.github.xiaoymin.knife4j.core.util.CollectionUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.MediaType;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.reactive.function.BodyExtractors;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import reactor.core.CoreSubscriber;
import reactor.core.Disposable;
import reactor.core.publisher.BaseSubscriber;
import reactor.core.publisher.Flux;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.time.Duration;
import java.util.*;
import java.util.concurrent.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@RestController
@Slf4j
public class SseTestController {

    // 创建一个单线程的调度器
    private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);


    @Resource(name = "sseAsyncPoolTaskExecutor")
    private ThreadPoolTaskExecutor sseAsyncPoolTask;

    @GetMapping(path = "/sse", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public SseEmitter streamSseMvc() {
        SseEmitter emitter = new SseEmitter(60_000L); // 设置超时时间为60秒

        // 启动定时任务，每秒发送一次消息
        scheduler.scheduleAtFixedRate(() -> {
            try {
                // 发送数据
                emitter.send(SseEmitter.event()
                        .id(String.valueOf(System.currentTimeMillis()))
                        .name("message")
                        .data("Hello, SSE! Time: " + System.currentTimeMillis()));
            } catch (IOException e) {
                // 发生异常时，完成发射器
                emitter.completeWithError(e);
            }
        }, 0, 1, TimeUnit.SECONDS);

        // 设置完成回调
        emitter.onCompletion(() -> System.out.println("SSE connection completed"));
        // 设置超时回调
        emitter.onTimeout(() -> {
            System.out.println("SSE connection timed out");
            emitter.complete();
        });
        // 设置错误回调
        emitter.onError((ex) -> {
            System.out.println("SSE connection error: " + ex.getMessage());
            emitter.completeWithError(ex);
        });

        return emitter;
    }


    @GetMapping(path = "/sse2", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public SseEmitter streamSseMvc2() {
        String logMsg = "sse接口 requestId: " + UUID.randomUUID();

        long startTime = System.currentTimeMillis();

        log.info("{} 开始时间:{} 请求参数:{}", logMsg, startTime, "ceshi");
        SseEmitter emitter = new SseEmitter(1800_000L);
        Callable<SseEmitter> task = () -> {
            try {
//                SearchConfirmOutputDTO outputDTO = new SearchConfirmOutputDTO();
//                SearchQuestionBaseBO searchQuestionBaseBO = new SearchQuestionBaseBO();
//
//                String jwt = inputDTO.getJwt();
//                String psId = inputDTO.getPsId();
//                String userId = inputDTO.getUserId();
//                String inputQuestionId = inputDTO.getQuestionId();
//                Integer inputSubject = inputDTO.getSubject();
//
//                String questionId = inputQuestionId;
//                Integer subject = null;
//                Integer type = inputDTO.getType();
//                // 参数校验
//                if (StringUtils.isBlank(psId) && StringUtils.isBlank(inputQuestionId)) {
//                    SseUtils.sendSseMessage(emitter, ToolUtils.uniqueID(),
//                            "error", "输入参数错误 psId 和 questionId 不能同时为空", 300L);
//                    SseUtils.completeEmitterNullData(emitter, ToolUtils.uniqueID());
//                    return emitter;
//                }
//
//                long psStartTime = System.currentTimeMillis();
//                log.info("{} 调用底层拍搜 开始时间:{}", logMsg, psStartTime);
//                XueXiaoBanResponseVo responseVo = new XueXiaoBanResponseVo();
//                String csId = UUIDUtils.generateUUIDWithoutHyphens();
//
//                String questionLang = null;
//                Integer gradeId = 0;
//                String ocrText = null;
//                String imgUrl = null;
//                String imgType = null;
//
//                String solution = null;
//                Integer questionType = null;
//                Float score = null;
//                Integer gradeGroup = null;
//                Float esScore = null;
//                String singleAnswer = null;
//                String solutionScoreTagValue = null;
//                String solutionSourceTagVersion = null;
//                String solutionSourceTagValue = null;
//                String questionOld = null;
//                // 给端上的 question
//                String question = null;
//                // 给端上的
//                String answer = null;
//
//                String chineseEnglishExamplePsId = null;
//
//                String queType = null;
//
//                Boolean isChineseEnglishExample = isChineseEnglishExampleQuestion(inputSubject, type);
//
//                if (StringUtils.isNotBlank(psId)) {
//                    // 0.查询讲题确认存储的拍搜数据
//                    QueryWrapper<PhotoSearch> queryWrapper = new QueryWrapper<>();
//                    queryWrapper.eq("ps_id", psId);
//                    PhotoSearch photoSearch = photoSearchMapper.selectOne(queryWrapper);
//
//                    if (ObjectUtils.isEmpty(photoSearch)) {
//                        SseUtils.sendSseMessage(emitter, ToolUtils.uniqueID(),
//                                "error", "未找到拍搜相关数据 psId:" + psId, 300L);
//                        SseUtils.completeEmitterNullData(emitter, ToolUtils.uniqueID());
//                        return emitter;
//                    }
//                    questionLang = photoSearch.getQuestionLang();
//                    subject = photoSearch.getSubject();
//                    gradeId = photoSearch.getGradeId();
//                    ocrText = photoSearch.getContent();
//                    imgUrl = photoSearch.getImgUrl();
//                    imgType = photoSearch.getImgType();
//                    queType = photoSearch.getQueType();
//                }
//
//                // 1.调用底层拍搜
//                QuestionSearchRequestParam searchRequestParam = new QuestionSearchRequestParam();
//                // 基础查询参数
//                searchRequestParam.setTopNum(1);
//                searchRequestParam.setQuestionLang(questionLang);
//                searchRequestParam.setQuestionId(inputQuestionId);
//                searchRequestParam.setSubject(inputSubject != null ? inputSubject : subject);
//                searchRequestParam.setQuestion(ocrText);
//                searchRequestParam.setImgType(imgType);
//
//                searchRequestParam.setCheckScore(true);
//                searchRequestParam.setNeedPrm(true);
//                searchRequestParam.setRequestId(requestId);
//                searchRequestParam.setXChannel(channel);
//                searchRequestParam.setJwt(jwt);
//                // 此处只处理示例题
//                if (type == 2) {
//                    if (inputSubject == 2) {
//                        try {
//                            responseVo = exquisiteQuestionSearchService.askAnytimeSearch(searchRequestParam);
//                        } catch (UnsupportedEncodingException | NoSuchAlgorithmException | InvalidKeyException |
//                                 JsonProcessingException e) {
//                            throw new RuntimeException(e);
//                        }
//                    }
//                    if (inputSubject == 4 || inputSubject == 5) {
//                        try {
//                            responseVo = perfectQuestionSearchService.searchBySubject(searchRequestParam);
//                        } catch (Exception e) {
//                            throw new RuntimeException(e);
//                        }
//                    }
//                    // 语文英语 【示例题】 直接单独查询 无需直出
//                    if (isChineseEnglishExample){
//                        chineseEnglishExamplePsId = ToolUtils.uniqueID();
//                        responseVo.setPsId(chineseEnglishExamplePsId);
//                        responseVo.setQuestionVariant(1);
//                        subject = inputSubject;
//                        QueryWrapper<SpeakChineseEnglishQuestion> queryWrapper =
//                                new QueryWrapper<SpeakChineseEnglishQuestion>().eq("question_id", questionId);
//                        SpeakChineseEnglishQuestion speakChineseEnglishQuestion =
//                                speakChineseEnglishQuestionMapper.selectOne(queryWrapper);
//
//                        if (ObjectUtils.isNotEmpty(speakChineseEnglishQuestion)){
//                            ocrText = speakChineseEnglishQuestion.getQuestion();
//                            question = ocrText;
//                            questionOld = ocrText;
//                            questionType = 1;
//                            gradeId = speakChineseEnglishQuestion.getGradeId();
//                            singleAnswer = speakChineseEnglishQuestion.getAnswer();
//                            solution = speakChineseEnglishQuestion.getSolution();
//                            if (StringUtils.isBlank(solution)) {
//                                // 通过直出兜底
//                                responseVo.setQuestionVariant(4);
//                            }else {
//                                answer = solution;
//                            }
//                        }
//                        PhotoSearch photoSearch = new PhotoSearch();
//                        photoSearch.setPsId(chineseEnglishExamplePsId);
//                        photoSearch.setType(type);
//                        photoSearch.setUserId(userId);
//                        Integer explainStatus = getExplainStatus(subject);
//                        photoSearch.setSubject(subject);
//                        photoSearch.setExplainStatus(explainStatus);
//                        photoSearch.setImgType(ImgTypeEnum.TEXT.getName());
//                        photoSearch.setQueType(QueTypeEnum.Others.getName());
//                        photoSearch.setContent(ocrText);
//                        photoSearch.setQuestionId(questionId);
//                        photoSearch.setTop1Id(questionId);
//                        photoSearch.setQuestionType(questionType);
//                        photoSearch.setChannel(channel);
//                        photoSearch.setGradeId(gradeId);
//                        photoSearch.setTop1Solution(solution);
//                        photoSearch.setTop1Answer(singleAnswer);
//                        gradeGroup = getGradeGroupById(gradeId);
//                        photoSearch.setPeriod(gradeGroup);
//                        photoSearchMapper.insert(photoSearch);
//                    }
//                } else {
//                    // 语文 英语 非示例题 直接走直出
//                    if (subject != null && (subject == 1 || subject == 3)) {
//                        responseVo.setQuestionVariant(4);
//                    }else if(subject != null && (subject == 4 || subject == 5)){
//                        try {
//                            responseVo = perfectQuestionSearchService.searchBySubject(searchRequestParam);
//                        } catch (Exception e) {
//                            throw new RuntimeException(e);
//                        }
//                    }else {
//                        //查询数学
//                        try {
//                            responseVo = exquisiteQuestionSearchService.askAnytimeSearch(searchRequestParam);
//                        } catch (UnsupportedEncodingException | JsonProcessingException | NoSuchAlgorithmException |
//                                 InvalidKeyException e) {
//                            throw new RuntimeException(e);
//                        }
//                    }
//                }
//                long psEndTime = System.currentTimeMillis();
//                log.info("{} 调用底层拍搜 结束时间:{} 耗时:{}", logMsg, psEndTime, psEndTime - psStartTime);
//                // 调用底层search返回的 psId
//                String searchPsId = responseVo.getPsId();
//                List<XueXiaoBanResponseVo.Results> resultsList = responseVo.getResults();
//                Integer questionVariant = responseVo.getQuestionVariant();
//
//                Disposable disposable = null;
//                searchQuestionBaseBO.setQuestionVariant(questionVariant);
//                if (CollectionUtils.isEmpty(resultsList)) {
//                    // 是语文英语示例题，同时无需直出精美解析
//                    if (isChineseEnglishExample && questionVariant != 4){
//                        searchQuestionBaseBO.setQuestionVariant(1);
//                        searchQuestionBaseBO.setQuestionId(questionId);
//                        searchQuestionBaseBO.setQuestion(question);
//
//                        long questionBaseStartTime = System.currentTimeMillis();
//                        log.info("{} 发送 questionBase 开始时间:{}", logMsg, questionBaseStartTime);
//                        SseUtils.sendSseMessage(emitter, ToolUtils.uniqueID(), "questionBase",
//                                JSON.toJSONString(searchQuestionBaseBO), 300L);
//                        long questionBaseEndTime = System.currentTimeMillis();
//                        log.info("{} 发送 questionBase 结束时间:{} 耗时:{}", logMsg, questionBaseEndTime,
//                                questionBaseEndTime - questionBaseStartTime);
//
//                        // solution 精美解析开始 标记
//                        SseUtils.sendSseMessage(emitter, ToolUtils.uniqueID(), "solutionStart", "", 100L);
//
//                        // 存储到数据库的 原始
//                        long perfectStartTime = System.currentTimeMillis();
//                        log.info("{} 精美解析 开始时间:{}", logMsg, perfectStartTime);
//                        List<PerfectAnalysisDirectBO> perfectAnalysisDirectBOList = formatSolution(solution);
//                        for (PerfectAnalysisDirectBO perfectAnalysisDirectBO : perfectAnalysisDirectBOList) {
//                            SseUtils.sendSseMessage(emitter, ToolUtils.uniqueID(), "solution",
//                                    JSONObject.toJSONString(perfectAnalysisDirectBO), 100L);
//                        }
//                        long perfectEndTime = System.currentTimeMillis();
//                        log.info("{} 精美解析 结束时间:{} 耗时:{}", logMsg, perfectEndTime, perfectEndTime - perfectStartTime);
//
//                    }
//                    // 题目类型 原题 相似题 直出
//                    if (questionVariant != null && questionVariant == 4) {
//
//                        question = ocrText;
//                        questionOld = ocrText;
//                        questionId = UUIDUtils.generateUUIDWithoutHyphens();
//                        questionType = 4;
//                        searchQuestionBaseBO.setQuestionId(questionId);
//                        searchQuestionBaseBO.setQuestion(question);
//                        long questionBaseStartTime = System.currentTimeMillis();
//                        log.info("{} 发送 questionBase 开始时间:{}", logMsg, questionBaseStartTime);
//                        SseUtils.sendSseMessage(emitter, ToolUtils.uniqueID(), "questionBase",
//                                JSON.toJSONString(searchQuestionBaseBO), 300L);
//                        long questionBaseEndTime = System.currentTimeMillis();
//                        log.info("{} 发送 questionBase 结束时间:{} 耗时:{}", logMsg, questionBaseEndTime,
//                                questionBaseEndTime - questionBaseStartTime);
//
//                        // solution 精美解析开始 标记
//                        SseUtils.sendSseMessage(emitter, ToolUtils.uniqueID(), "solutionStart", "", 100L);
//
//
//                        // todo 调用算法精美解析直出接口
//                        long perfectStartTime = System.currentTimeMillis();
//                        log.info("{} 精美解析【直出】 开始时间:{}", logMsg, perfectStartTime);
//
//
//                        PerfectAnalysisRequestDTO dto = PerfectAnalysisRequestDTO.builder()
//                                .question(question)
//                                .sessionId(csId)
//                                .textOrImage(0)
//                                .subject(subject)
//                                .grade(gradeId)
//                                .imageUrls(Collections.emptyList())
//                                .ragNum(3)
//                                .searchResult(Collections.emptyList())
//                                .queType(queType)
//                                .requestId(UUID.randomUUID().toString())
//                                .build();
//
//                        // 如果是解题直出的话，手动调用精美解析
//                        log.info("{} 精美解析【直出】请求相关参数:{}", logMsg, JSON.toJSONString(dto));
//                        // 全量缓冲区：记录所有接收到的原始数据
//                        StringBuilder completeBuffer = new StringBuilder();
//                        // 创建 WebClient 请求流
//                        Flux<String> flux = webClient.post()
//                                .uri(perfectAnalysisUrl)
//                                .header("Authorization", perfectAnalysisAuthorization)
//                                .contentType(MediaType.APPLICATION_JSON)
//                                .body(BodyInserters.fromValue(JSON.toJSONString(dto)))
//                                .exchangeToFlux(response -> {
//                                    if (response.statusCode().is2xxSuccessful()) {
//                                        // 使用UTF-8缓冲处理器来避免字符截断
//                                        return directExplainScriptService.createUtf8BufferedFlux(response.body(BodyExtractors.toDataBuffers()));
//                                    } else {
//                                        return response.createException().flatMapMany(Flux::error);
//                                    }
//                                }).timeout(Duration.ofSeconds(60 * 5))
//                                .doOnError(e -> {
//                                    log.error(logMsg + "精美解析【直出】出错,请求相关参数: "+JSON.toJSONString(dto)+" 报错信息:", e);
//                                });
//
//                        // 自定义处理逻辑：按 <step> 分组
//                        Flux<String> stepFlux = flux.transform(f -> new Flux<String>() {
//
//                            @Override
//                            public void subscribe(CoreSubscriber<? super String> actual) {
//                                f.subscribe(new BaseSubscriber<String>() {
//                                    final StringBuilder buffer = new StringBuilder();
//
//                                    Queue<PerfectAnalysisDirectBO> queue = new LinkedList<>();
//
//                                    @Override
//                                    protected void hookOnNext(String sseStr) {
////                                        log.info("接收到的数据---长度:{}原始数据:\n{}", sseStr.length(), sseStr);
////                                        SseUtils.streamToJson(sseStr);
//                                        String data = SseUtils.getStreamData(sseStr);
//                                        // 累积数据到缓冲区
//                                        buffer.append(data);
//                                        // 记录全量的数据
//                                        completeBuffer.append(data);
//                                        processBuffer(actual);
//                                    }
//
//                                    @Override
//                                    protected void hookOnComplete() {
//                                        if (buffer.length() > 0) {
////                            log.warn("流结束，但存在未处理数据：{}", buffer.toString());
//                                        }
//                                        if (queue.size() == 1) {
//                                            PerfectAnalysisDirectBO perfectAnalysisDirectBO = queue.poll();
//                                            perfectAnalysisDirectBO.setIsLast(1);
//                                            actual.onNext(JSON.toJSONString(perfectAnalysisDirectBO));
//                                        } else {
//                                            log.info("标记最后一步出错");
//                                        }
//                                        // 正常关闭下游
//                                        actual.onComplete();
//                                    }
//
//                                    @Override
//                                    protected void hookOnError(Throwable throwable) {
//                                        actual.onError(throwable);
//                                    }
//
//                                    // 从缓冲区提取完整 <step> 标签并发送
//                                    private void processBuffer(CoreSubscriber<? super String> actual) {
//                                        String currentBuffer = buffer.toString();
//                                        Pattern pattern = Pattern.compile(
//                                                "<step\\s*index\\s*=\\s*\"([^\"]+)\">(.*?)</step>",
//                                                Pattern.DOTALL
//                                        );
//                                        Matcher matcher = pattern.matcher(currentBuffer);
//                                        int lastEnd = 0;
//                                        while (matcher.find()) {
//                                            String fullIndex = matcher.group(1);
//                                            String question = fullIndex.split("-")[0];
//                                            String step = fullIndex.split("-")[1];
//                                            String detail = matcher.group(2);
//
//                                            PerfectAnalysisDirectBO perfectAnalysisDirectBO = new PerfectAnalysisDirectBO();
//                                            perfectAnalysisDirectBO.setQuestion(question);
//                                            perfectAnalysisDirectBO.setStep(step);
//                                            perfectAnalysisDirectBO.setDetail(detail);
//                                            perfectAnalysisDirectBO.setTimestamp(System.currentTimeMillis() + "");
//                                            perfectAnalysisDirectBO.setIsLast(0);
//                                            queue.offer(perfectAnalysisDirectBO);
//                                            sendStep();
//                                            lastEnd = matcher.end();
//                                        }
//                                        if (lastEnd > 0) {
//                                            // 删除已处理的部分，保留未处理数据（如不完整的标签）
//                                            buffer.delete(0, lastEnd);
//                                        }
//                                    }
//
//                                    private void sendStep() {
//                                        if (queue.size() == 2) {
//                                            PerfectAnalysisDirectBO perfectAnalysisDirectBO = queue.poll();
//                                            actual.onNext(JSON.toJSONString(perfectAnalysisDirectBO));
//                                        }
//                                    }
//                                });
//                            }
//                        });
//
//                        // 订阅处理后的流 处理分块和全量缓冲区的订阅者
//                        CompletableFuture<Void> streamCompletion = new CompletableFuture<>();
//
//                        String finalChineseEnglishExamplePsId = chineseEnglishExamplePsId;
//                        disposable = stepFlux.subscribe(
//                                data -> SseUtils.sendSseMessage(emitter, ToolUtils.uniqueID(), "solution", data, 300L),
//                                error -> {
//                                    log.error(logMsg+  "精美解析【直出】出错,请求相关参数: "+JSON.toJSONString(dto)+" 流处理失败:", error);
//                                    streamCompletion.completeExceptionally(error);
//                                },
//                                () -> {
//                                    // 流完成时处理全量数据（例如持久化）
//                                    String fullData = completeBuffer.toString();
//                                    log.info("完整数据已接收，长度：{} 原始数据:{}", fullData.length(), fullData);
//                                    PhotoSearch updatePhotoSearch = new PhotoSearch();
//                                    String dataSolution = SolutionUtil.convertSolutionToJson(fullData);
//                                    log.info("处理后完整的存储数据库的直出 solution:{}", dataSolution);
//                                    updatePhotoSearch.setTop1Solution(StringUtils.isBlank(fullData) ? "" : dataSolution);
//                                    UpdateWrapper<PhotoSearch> updateWrapper = new UpdateWrapper<>();
//                                    if (StringUtils.isNotBlank(finalChineseEnglishExamplePsId)){
//                                        updateWrapper.eq("ps_id", finalChineseEnglishExamplePsId);
//                                    }else {
//                                        updateWrapper.eq("ps_id", psId);
//                                    }
//                                    photoSearchMapper.update(updatePhotoSearch, updateWrapper);
//                                    redisUtils.delKey(CommonConstant.MATH_AT_PHOTO_SEARCH_INFO_KEY + psId);
//                                    streamCompletion.complete(null);
//                                }
//                        );
//
//                        try {
//                            streamCompletion.get(30, TimeUnit.SECONDS);
//                            QueryWrapper<PhotoSearch> queryWrapper = new QueryWrapper<>();
//                            if (StringUtils.isNotBlank(finalChineseEnglishExamplePsId)){
//                                queryWrapper.eq("ps_id", finalChineseEnglishExamplePsId);
//                            }else {
//                                queryWrapper.eq("ps_id", psId);
//                            }
//                            PhotoSearch photoSearch1 = photoSearchMapper.selectOne(queryWrapper);
//                            solution = photoSearch1.getTop1Solution();
//                            answer = solution;
//                            long perfectEndTime = System.currentTimeMillis();
//                            log.info("{} 精美解析【直出】 结束时间:{} 耗时:{}", logMsg, perfectEndTime,
//                                    perfectEndTime - perfectStartTime);
//                        } catch (TimeoutException e) {
//                            log.error(logMsg+  "精美解析【直出】出错,请求相关参数: "+JSON.toJSONString(dto)+" 等待流处理超时:", e);
//                        } catch (Exception e) {
//                            log.error(logMsg+  "精美解析【直出】出错,请求相关参数: "+JSON.toJSONString(dto)+" 执行失败:", e);
//                        }
//                    }
//                } else {
//                    XueXiaoBanResponseVo.Results results = resultsList.get(0);
//                    questionId = results.getQuestionId();
//                    questionType = questionVariant;
//                    // 给端上的 question
//                    question = results.getQuestion();
//
//                    searchQuestionBaseBO.setQuestionId(questionId);
//                    searchQuestionBaseBO.setQuestion(question);
//
//                    long questionBaseStartTime = System.currentTimeMillis();
//                    log.info("{} 发送 questionBase 开始时间:{}", logMsg, questionBaseStartTime);
//                    SseUtils.sendSseMessage(emitter, ToolUtils.uniqueID(), "questionBase",
//                            JSON.toJSONString(searchQuestionBaseBO), 300L);
//
//                    long questionBaseEndTime = System.currentTimeMillis();
//                    log.info("{} 发送 questionBase 结束时间:{} 耗时:{}", logMsg, questionBaseEndTime,
//                            questionBaseEndTime - questionBaseStartTime);
//
//                    // solution 精美解析开始 标记
//                    SseUtils.sendSseMessage(emitter, ToolUtils.uniqueID(), "solutionStart", "", 100L);
//
//                    // 存储到数据库的 原始
//                    long perfectStartTime = System.currentTimeMillis();
//                    log.info("{} 精美解析 开始时间:{}", logMsg, perfectStartTime);
//                    questionOld = results.getQuestionOld() == null ? question : results.getQuestionOld();
//                    // 给端上的
//                    answer = results.getAnswer();
//
//                    // 存储到数据库的 原始
//                    solution = results.getSolution() == null ? answer : results.getSolution();
//
//                    List<PerfectAnalysisDirectBO> perfectAnalysisDirectBOList = formatSolution(answer);
//                    for (PerfectAnalysisDirectBO perfectAnalysisDirectBO : perfectAnalysisDirectBOList) {
//                        SseUtils.sendSseMessage(emitter, ToolUtils.uniqueID(), "solution",
//                                JSONObject.toJSONString(perfectAnalysisDirectBO), 100L);
//                    }
//                    long perfectEndTime = System.currentTimeMillis();
//                    log.info("{} 精美解析 结束时间:{} 耗时:{}", logMsg, perfectEndTime, perfectEndTime - perfectStartTime);
//
//                    gradeId = results.getGrade();
//                    questionLang = results.getQuestionLang();
//
//                    Integer esTop = results.getEsTop();
//                    esScore = results.getEsScore();
//                    gradeGroup = results.getGradeGroup() == null ? getGradeGroupById(gradeId) : results.getGradeGroup();
//
//                    Integer questionCategory = results.getQuestionCategory();
//                    score = results.getScore();
//                    Float similarScore = results.getSimilarScore();
//                    singleAnswer = results.getSingleAnswer();
//                    String solutionVersion = results.getSolutionVersion();
//                    String tokenContent = results.getTokenContent();
//
//                    List<TagVo> tags = results.getTags();
//                    TagVo solutionScoreTag = getSpecialTagVo(tags, "solution_score");
//                    solutionScoreTagValue = solutionScoreTag.getValue();
//                    TagVo solutionSourceTag = getSpecialTagVo(tags, "source");
//                    solutionSourceTagValue = solutionSourceTag.getValue();
//                    solutionSourceTagVersion = solutionScoreTag.getVersion();
//                    TagVo hasImgTag = getSpecialTagVo(tags, "has_img");
//                    String hasImgTagValue = hasImgTag.getValue();
//                }
//                // 回填 photo_search数据
//                if (!isChineseEnglishExample) {
//                    if (StringUtils.isNotBlank(psId)) {
//                        PhotoSearch updatePhotoSearch = new PhotoSearch();
//                        updatePhotoSearch.setPsId(psId);
//                        updatePhotoSearch.setType(type);
//                        updatePhotoSearch.setQuestionId(questionId);
//                        updatePhotoSearch.setQuestionType(questionType);
//                        updatePhotoSearch.setTop1Id(questionId);
//                        updatePhotoSearch.setTop1Score(score != null ? score.toString() : "");
//                        updatePhotoSearch.setTop1EsScore(esScore != null ? esScore.toString() : "");
//                        updatePhotoSearch.setTop1Solution(solution);
//                        updatePhotoSearch.setTop1Answer(singleAnswer);
//                        updatePhotoSearch.setTop1SolutionScore(solutionScoreTagValue);
//                        updatePhotoSearch.setTop1SolutionVersion(solutionSourceTagVersion);
//                        updatePhotoSearch.setTop1Source(solutionSourceTagValue == null ? 0 : Integer.parseInt(solutionSourceTagValue));
//
//                        UpdateWrapper<PhotoSearch> updateWrapper = new UpdateWrapper<>();
//                        updateWrapper.eq("ps_id", psId);
//                        photoSearchMapper.update(updatePhotoSearch, updateWrapper);
//                        redisUtils.delKey(CommonConstant.MATH_AT_PHOTO_SEARCH_INFO_KEY + psId);
//                    } else {
//                        PhotoSearch photoSearch = new PhotoSearch();
//                        photoSearch.setPsId(searchPsId);
//                        photoSearch.setType(type);
//                        photoSearch.setUserId(userId);
//                        subject = subject != null ? subject : inputSubject;
//                        Integer explainStatus = getExplainStatus(subject);
//                        photoSearch.setSubject(subject);
//                        photoSearch.setExplainStatus(explainStatus);
//                        photoSearch.setImgType(ImgTypeEnum.TEXT.getName());
//                        photoSearch.setQueType(QueTypeEnum.Others.getName());
//                        photoSearch.setQuestionLang(questionLang);
//                        photoSearch.setChannel(channel);
//                        photoSearch.setGradeId(gradeId);
//                        photoSearch.setPeriod(gradeGroup);
//
//                        photoSearch.setQuestionId(questionId);
//                        photoSearch.setQuestionType(questionType);
//                        photoSearch.setTop1Id(questionId);
//                        photoSearch.setTop1Score(score != null ? score.toString() : "");
//                        photoSearch.setTop1EsScore(esScore != null ? esScore.toString() : "");
//                        photoSearch.setTop1Solution(solution);
//                        photoSearch.setTop1Answer(singleAnswer);
//                        photoSearch.setTop1SolutionScore(solutionScoreTagValue);
//                        photoSearch.setTop1SolutionVersion(solutionSourceTagVersion);
//                        photoSearch.setTop1Source(solutionSourceTagValue == null ? 0 :
//                                Integer.parseInt(solutionSourceTagValue));
//                        photoSearchMapper.insert(photoSearch);
//                    }
//                }
//
//
//                // 创建主会话
//                Conversations conversations = new Conversations();
//                conversations.setCsId(csId);
//                if (StringUtils.isNotBlank(psId)) {
//                    conversations.setPsId(psId);
//                } else {
//                    conversations.setPsId(searchPsId);
//                }
//                conversations.setImgUrl(imgUrl);
//                conversations.setQuestionId(questionId);
//                conversations.setQuestion(questionOld == null ? question : questionOld);
//                conversations.setUser1Id(userId);
//                conversations.setUser2Id("2");
//                conversations.setType(2);
//                // 课堂主会话
//                conversations.setSessionType(1);
//                conversations.setQuestionType(questionType);
//                conversations.setSolution(solution);
//                conversations.setAnswer(singleAnswer);
//                conversations.setChannel(channel);
//                conversations.setSubject(subject);
//                conversationsMapper.insert(conversations);
//
//                //错题拍搜进来的
//                if (Objects.equals(inputDTO.getType(), 7) && EmptyHelper.isNotEmpty(inputDTO.getSourceId())) {
//                    WrongQuestionRecord record = new WrongQuestionRecord();
//                    record.setWrongId(inputDTO.getSourceId());
//                    record.setPsId(psId);
//                    record.setCsId(csId);
//                    record.setQuestionId(questionId);
//                    wrongQuestionService.updateByWrongId(record);
//                }
//
//                // solution 精美解析结束 标记
//                SseUtils.sendSseMessage(emitter, ToolUtils.uniqueID(), "solutionEnd", "", 100L);
//
//                long sessionIdStartTime = System.currentTimeMillis();
//                log.info("{} 发送 sessionId 开始时间:{}", logMsg, sessionIdStartTime);
//                SseUtils.sendSseMessage(emitter, ToolUtils.uniqueID(), "sessionId", csId, 300L);
//                long sessionIdEndTime = System.currentTimeMillis();
//                log.info("{} 发送 sessionId 结束时间:{} 耗时:{}", logMsg, sessionIdEndTime, sessionIdEndTime - sessionIdStartTime);
//
//                try {
//                    // 学情分析接口适配新版：创建主会话后需要调用
//                    StudyReport studyReport = new StudyReport();
//                    studyReport.setPsId(conversations.getPsId());
//                    studyReport.setType(1);
//                    long reportStartTime = System.currentTimeMillis();
//                    log.info("学情分析接口适配新版 开始时间:{}", reportStartTime);
//                    studyReportService.saveReport(studyReport);
//                    long reportEndTime = System.currentTimeMillis();
//                    log.info("学情分析接口适配新版 结束时间:{} 耗时 {}ms", reportEndTime, reportEndTime - reportStartTime);
//                } catch (Exception e) {
//                    log.error("调用 学情分析接口适配新版时出错 ", e);
//                }
//
//                outputDTO.setSessionId(csId);
//                outputDTO.setQuestionId(questionId);
//                outputDTO.setQuestion(question);
//                outputDTO.setSolution(answer);
//
//                long recommendStartTime = System.currentTimeMillis();
//                log.info("{} 推荐问题 开始时间:{}", logMsg, recommendStartTime);
//
//                MultiModalProbeParam multiModalProbeParam = new MultiModalProbeParam();
//                multiModalProbeParam.setSession_id(csId);
//
//                JSONObject followupConfig = new JSONObject();
//                // question_confirm: 题目确认页推荐问题 explanation_complete: 小思/小智讲完后推荐问题
//                followupConfig.put("type", "question_confirm");
//                multiModalProbeParam.setFollowup_config(followupConfig);
//
//                List<MultiModalExplainParam.Prompt> promptList = new ArrayList<>();
//                List<MultiModalExplainParam.Prompt> historyListExplain = new ArrayList<>();
//                multiModalProbeParam.setPrompt(promptList);
//                multiModalProbeParam.setHistory(historyListExplain);
//
//                List<MultiModalExplainParam.Solution> solutions = getSolutionDetail(solution);
//                MultiModalExplainParam.PerfectAnalysis perfectAnalysis = new MultiModalExplainParam.PerfectAnalysis();
//                perfectAnalysis.setAnswer(solutions);
//                perfectAnalysis.setQuestion_id(conversations.getQuestionId());
//                perfectAnalysis.setQuestion(conversations.getQuestion());
//                perfectAnalysis.setGrade_id(gradeId);
//                perfectAnalysis.setSubject(subject);
//                multiModalProbeParam.setPerfectAnalysis(perfectAnalysis);
//                List<String> recommendQuestionList = computeService.getRecommendQuestion(multiModalProbeParam, requestId);
//                outputDTO.setRecommendQuestionList(recommendQuestionList);
//
//                String recommendContent = JSON.toJSONString(recommendQuestionList);
//                SseUtils.sendSseMessage(emitter, ToolUtils.uniqueID(), "recommendQuestion",
//                        recommendContent, 300L);
//                long recommendEndTime = System.currentTimeMillis();
//                log.info("{} 推荐问题 结束时间:{} 耗时:{}", logMsg, recommendEndTime, recommendEndTime - recommendStartTime);
//
//
//                // 存储推荐问题到 messages
//                if (CollectionUtils.isNotEmpty(recommendQuestionList)) {
//                    Messages messages = new Messages();
//                    String mid = UUIDUtils.generateUUIDWithoutHyphens();
//                    messages.setMid(mid);
//                    if (StringUtils.isNotBlank(psId)) {
//                        messages.setPsId(psId);
//                    } else {
//                        messages.setPsId(searchPsId);
//                    }
//                    messages.setCsId(csId);
//                    messages.setContent(recommendContent);
//                    messages.setHtmlContent(recommendContent);
//                    messages.setQuestionId(questionId);
//                    messages.setSenderId("2");
//                    messages.setReceiverId(userId);
//                    messages.setType(2);
//                    messages.setMType(2);
//                    messages.setChannel(channel);
//                    BigInteger bigInteger = new BigInteger(String.valueOf(System.currentTimeMillis()));
//                    messages.setCreateTime(bigInteger);
//                    messagesMapper.insert(messages);
//                }
//
//                if (disposable != null) {
//                    disposable.dispose();
//                }

                SseUtils.completeEmitterNullData(emitter, UUIDUtils.generateUUID());
                return emitter;
            } catch (Exception e) {
                emitter.completeWithError(e);
                log.error("拍搜确认接口异常",e);
            } finally {

            };
            return emitter;
        };
        sseAsyncPoolTask.submit(task);

        SseUtils.setupEmitterCallbacks(emitter);
        long endTime = System.currentTimeMillis();
        log.info("{} 结束时间:{} 耗时:{}", logMsg, endTime, endTime - startTime);

        return emitter;
    }


}
